package org.springblade.modules.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.quartz.*;
import org.springblade.modules.platform.config.ScheduleConstants;
import org.springblade.modules.platform.entity.SysJob;
import org.springblade.modules.platform.job.TaskException;
import org.springblade.modules.platform.mapper.SysJobMapper;
import org.springblade.modules.platform.service.ISysJobService;
import org.springblade.modules.platform.utils.ScheduleUtils;
import org.springblade.modules.platform.vo.SysJobListVO;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 定时任务调度表 服务实现类
 * </p>
 *
 * @author SYG
 * @since 2022-08-24
 */
@Service
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements ISysJobService {

	@Autowired
	private Scheduler scheduler;
	/**
	 * 获取quartz调度器的计划任务列表
	 *
	 * @param sysJob 调度信息
	 * @return
	 */
	@Override
	public SysJobListVO selectJobList(SysJob sysJob, Query query) {
		SysJobListVO sysJobListVO = new SysJobListVO();
		LambdaQueryWrapper<SysJob> queryWrapper = new LambdaQueryWrapper();
		if(sysJob.getJobId()!=null){
			queryWrapper.eq(SysJob::getJobId,sysJob.getJobId());
		}
		if(!StringUtils.isEmpty(sysJob.getJobName())){
			queryWrapper.like(SysJob::getJobName,sysJob.getJobName());
		}
		Page<SysJob> sysJobPage = baseMapper.selectPage(new Page<SysJob>(query.getCurrent(), query.getSize()), queryWrapper);
		long total = sysJobPage.getTotal();
		sysJobListVO.setTotal(total);
		sysJobListVO.setRecords(sysJobPage.getRecords());

		return sysJobListVO;
	}
	/**
	 * 通过调度任务ID查询调度信息
	 *
	 * @param jobId 调度任务ID
	 * @return 调度任务对象信息
	 */
	@Override
	public SysJob selectJobById(Long jobId) {
		return baseMapper.selectById(jobId);
	}

	@Override
	public SysJob insertJob(SysJob job) throws SchedulerException, TaskException {
		job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
		job.setCreateBy(AuthUtil.getNickName());
		job.setCreateTime(new Date());
		job.setUpdateTime(new Date());
		int rows = baseMapper.insert(job);
		if (rows > 0) {
			ScheduleUtils.createScheduleJob(scheduler, job);
		}
		return job;

	}

	@Override
	public int updateJob(SysJob job) throws SchedulerException, TaskException {
		SysJob properties = selectJobById(job.getJobId());
		int rows = baseMapper.updateById(job);
		if (rows > 0) {
			updateSchedulerJob(job, properties.getJobGroup());
		}
		return 0;
	}
	/**
	 * 更新任务
	 *
	 * @param job 任务对象
	 * @param jobGroup 任务组名
	 */
	public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {
		Long jobId = job.getJobId();
		// 判断是否存在
		JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
		if (scheduler.checkExists(jobKey)) {
			// 防止创建时存在数据问题 先移除，然后在执行创建操作
			scheduler.deleteJob(jobKey);
		}
		ScheduleUtils.createScheduleJob(scheduler, job);
	}
	/**
	 * 校验cron表达式是否有效
	 *
	 * @param cronExpression 表达式
	 * @return 结果
	 */
	@Override
	public boolean checkCronExpressionIsValid(String cronExpression) {

		return CronExpression.isValidExpression(cronExpression);

	}

	@Override
	public int changeStatus(SysJob job) throws SchedulerException {
		int rows = 0;
		String status = job.getStatus();
		if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
			rows = resumeJob(job);
		}
		else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
			rows = pauseJob(job);
		}
		return rows;
	}

	@Override
	public void run(SysJob job) throws SchedulerException {
		Long jobId = job.getJobId();
		String jobGroup = job.getJobGroup();
		SysJob properties = selectJobById(job.getJobId());
		// 参数
		JobDataMap dataMap = new JobDataMap();
		dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
		scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap);
	}

	@Override
	public void deleteJobByIds(List<Long>  jobIds) throws SchedulerException {
		for (Long jobId : jobIds) {
			SysJob job = baseMapper.selectById(jobId);
			deleteJob(job);
		}

	}
	@Override
	public void deleteJobById(Long  jobId) throws SchedulerException {
		SysJob job = baseMapper.selectById(jobId);
		deleteJob(job);

	}
	/**
	 * 删除任务后，所对应的trigger也将被删除
	 *
	 * @param job 调度信息
	 */
	@Override
	@Transactional
	public int deleteJob(SysJob job) throws SchedulerException {
		Long jobId = job.getJobId();
		String jobGroup = job.getJobGroup();
		int rows = baseMapper.deleteById(jobId);
		if (rows > 0) {
			scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
		}
		return rows;
	}

	@Override
	public List<SysJob> selectJobByJobGroup(List jobGroup) {
		return baseMapper.selectList(Wrappers.<SysJob>query().lambda().in(SysJob::getJobGroup,jobGroup));
	}

	/**
	 * 恢复任务
	 *
	 * @param job 调度信息
	 */
	@Override
	@Transactional
	public int resumeJob(SysJob job) throws SchedulerException {
		Long jobId = job.getJobId();
		String jobGroup = job.getJobGroup();
		job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
		int rows = baseMapper.updateJob(job);
		if (rows > 0) {
			scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
		}
		return rows;
	}
	/**
	 * 暂停任务
	 *
	 * @param job 调度信息
	 */
	@Override
	@Transactional
	public int pauseJob(SysJob job) throws SchedulerException {
		Long jobId = job.getJobId();
		String jobGroup = job.getJobGroup();
		job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
		int rows = baseMapper.updateJob(job);
		if (rows > 0) {
			scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
		}
		return rows;
	}
}
